import { ApiResponse, SearchRes, Suggestion } from '@/types/data'
import { RootThunkAction, SearchAction } from '@/types/store'
import request from '@/utils/request'
import { removeLocalHistory, setLocalHistory } from '@/utils/storage'

//获取关键词联想列表
export const getSuggestionList = (keyWord: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ options: Suggestion }>>(
      '/suggestion',
      {
        params: {
          q: keyWord,
        },
      }
    )
    // console.log(res.data.data.options)
    let list: Suggestion
    list = res.data.data.options[0] === null ? [] : res.data.data.options
    dispatch({
      type: 'search/getSuggestionList',
      payload: list,
    })
  }
}

//添加保存历史记录
export const addHistory = (keyWord: string): RootThunkAction => {
  return (dispatch, getState) => {
    //会有功能
    let histories = getState().search.history
    //1.需要基于keyWord,判断是否重复，
    //如果重复，需要删除旧的，在前面新增新的
    histories = histories.filter((item) => item !== keyWord)
    //2.需要基于keyWord,判断长度是否超了，
    //需要删除最后一个
    if (histories.length >= 10) {
      histories.pop()
    }

    //在前面新增
    histories = [keyWord, ...histories]

    //3.需要将操作完的结果，存redux 存本地
    dispatch({
      type: 'search/saveHistoryList',
      payload: histories,
    })

    setLocalHistory(histories)
  }
}

//清除历史记录
export const clearHistory = (): RootThunkAction => {
  return (dispatch) => {
    //清空本地历史记录
    removeLocalHistory()
    //清空redux数据
    dispatch({
      type: 'search/clearHistories',
    })
  }
}

//删除某个历史记录
export const delHistory = (key: string): RootThunkAction => {
  return (dispatch, getState) => {
    //1. 从搜索历史数组中, 移除key这项 => 保留所有其他的
    let histories = getState().search.history
    histories = histories.filter((item) => item !== key)
    dispatch({
      type: 'search/saveHistoryList',
      payload: histories,
    })

    // 2.将最新的更新后的结果, 更新到本地
    setLocalHistory(histories)
  }
}

//获取搜索结果数据
export const getSearchResults = (
  page: number,
  keyWord: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<SearchRes>>('/search', {
      params: {
        q: keyWord,
        page,
        per_page: 10,
      },
    })
    // console.log(res.data.data, 78)
    dispatch({
      type: 'search/saveResults',
      payload: res.data.data,
    })
  }
}

//重置resultsObj
export const clearResObj = (): SearchAction => {
  return {
    type: 'search/clearResObj',
  }
}
